import { Link, Navigate, useParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';

import postApis from '../../../../apis/posts';
import ErrorInfo from '../../../../components/ui/ErrorInfo';
import List from '../../../../components/ui/List';
import Card from '../../../../components/ui/Card';
import { toCollectionId } from '../../../params/collection-id';

export default function Page() {
  const { id } = useParams();
  const result = toCollectionId(id);
  if (result.ok) {
    return <PostCollections collectionId={result.result} />;
  } else {
    return <Navigate to="/me/post-collections" />;
  }
}

function PostCollections({ collectionId }: { collectionId: number }) {
  const { status, data, error } = useQuery({
    queryKey: ['my-collectioned-posts', collectionId],
    queryFn: () => postApis.getPosts({ collectionId: +collectionId }),
  });

  if (status === 'pending') {
    return <div>loading...</div>;
  }

  if (status === 'error') {
    return <ErrorInfo error={error} />;
  }

  if (data.length === 0) {
    return (
      <Card className="w-full text-center">
        暂无文章，
        <Link className="underline" to={`/create-post?collectionId=${collectionId}`}>
          戳这里创建文章
        </Link>
      </Card>
    );
  }

  return (
    <Card noPadding className="w-full">
      <div className="border-b px-4 py-2 font-bold flex justify-between">
        文章列表
        <Link className="underline" to={`/create-post?collectionId=${collectionId}`}>
          创建文章
        </Link>
      </div>
      <List items={data} toKey={(it) => it.id}>
        {(item) => <div><Link to={`/posts/${item.id}`}>{item.title}</Link></div>}
      </List>
    </Card>
  );
}
